//
//  MapResultViewController.m
//  myhuibao
//
//  Created by li jun on 13-5-9.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "MapResultViewController.h"
#import "CallOutAnnotationVifew.h"
#import "JingDianMapCell.h"
#import "Config.h"
#import "RestaurantDetailViewController.h"
#define span 400000
#define MERCATOR_OFFSET 268435456
#define MERCATOR_RADIUS 85445659.44705395

@implementation MKMapView (ZoomLevel)

#pragma mark -
#pragma mark Map conversion methods

- (double)longitudeToPixelSpaceX:(double)longitude
{
    return round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * M_PI / 180.0);
}

- (double)latitudeToPixelSpaceY:(double)latitude
{
    return round(MERCATOR_OFFSET - MERCATOR_RADIUS * logf((1 + sinf(latitude * M_PI / 180.0)) / (1 - sinf(latitude * M_PI / 180.0))) / 2.0);
}

- (double)pixelSpaceXToLongitude:(double)pixelX
{
    return ((round(pixelX) - MERCATOR_OFFSET) / MERCATOR_RADIUS) * 180.0 / M_PI;
}

- (double)pixelSpaceYToLatitude:(double)pixelY
{
    return (M_PI / 2.0 - 2.0 * atan(exp((round(pixelY) - MERCATOR_OFFSET) / MERCATOR_RADIUS))) * 180.0 / M_PI;
}

#pragma mark -
#pragma mark Helper methods

- (MKCoordinateSpan)coordinateSpanWithMapView:(MKMapView *)mapView
                             centerCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                 andZoomLevel:(NSUInteger)zoomLevel
{
    // convert center coordiate to pixel space
    double centerPixelX = [self longitudeToPixelSpaceX:centerCoordinate.longitude];
    double centerPixelY = [self latitudeToPixelSpaceY:centerCoordinate.latitude];
    
    // determine the scale value from the zoom level
    NSInteger zoomExponent = 20 - zoomLevel;
    double zoomScale = pow(2, zoomExponent);
    
    // scale the map’s size in pixel space
    CGSize mapSizeInPixels = mapView.bounds.size;
    double scaledMapWidth = mapSizeInPixels.width * zoomScale;
    double scaledMapHeight = mapSizeInPixels.height * zoomScale;
    
    // figure out the position of the top-left pixel
    double topLeftPixelX = centerPixelX - (scaledMapWidth / 2);
    double topLeftPixelY = centerPixelY - (scaledMapHeight / 2);
    
    // find delta between left and right longitudes
    CLLocationDegrees minLng = [self pixelSpaceXToLongitude:topLeftPixelX];
    CLLocationDegrees maxLng = [self pixelSpaceXToLongitude:topLeftPixelX + scaledMapWidth];
    CLLocationDegrees longitudeDelta = maxLng - minLng;
    
    // find delta between top and bottom latitudes
    CLLocationDegrees minLat = [self pixelSpaceYToLatitude:topLeftPixelY];
    CLLocationDegrees maxLat = [self pixelSpaceYToLatitude:topLeftPixelY + scaledMapHeight];
    CLLocationDegrees latitudeDelta = -1 * (maxLat - minLat);
    
    // create and return the lat/lng span
    MKCoordinateSpan span1=MKCoordinateSpanMake(latitudeDelta, longitudeDelta);
    return span1;
}

#pragma mark -
#pragma mark Public methods

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated
{
    // clamp large numbers to 28
    zoomLevel = MIN(zoomLevel, 28);
    
    // use the zoom level to compute the region
    MKCoordinateSpan span1 = [self coordinateSpanWithMapView:self centerCoordinate:centerCoordinate andZoomLevel:zoomLevel];
    MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span1);
    
    // set the region like normal
    [self setRegion:region animated:animated];
}

@end


@interface MapResultViewController ()
{
    NSMutableArray *_annotationList;
    
    CalloutMapAnnotation *_calloutAnnotation;
	CalloutMapAnnotation *_previousdAnnotation;
    
}
-(void)setAnnotionsWithList:(NSArray *)list;

@end

@implementation MapResultViewController
@synthesize results;
@synthesize mapView=_mapView;

@synthesize delegate;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    _annotationList = [[NSMutableArray alloc] init];
    [super viewDidLoad];
    _mapView.delegate = self;
//    CLLocationCoordinate2D coordinate = {[[Config Instance]getLatitude],[[Config Instance]getLongitude]};
//    float zoomLevel =0.2; //设置显示精度
//    //确定显示初始位置
//    MKCoordinateRegion region =MKCoordinateRegionMake(coordinate,MKCoordinateSpanMake(zoomLevel, zoomLevel));
//    [self.mapView setRegion:region animated:YES];
//    self.mapView.centerCoordinate = coordinate;

}

-(void)setAnnotionsWithList:(NSArray *)list
{
    for (NSDictionary *dic in list) {
        if([dic valueForKey:@"latitude"] != [NSNull null]){

        CLLocationDegrees latitude=[[dic objectForKey:@"latitude"] doubleValue];
        CLLocationDegrees longitude=[[dic objectForKey:@"longtitude"] doubleValue];
            NSLog(@"%@",[dic objectForKey:@"latitude"]);
            NSLog(@"%@",[dic objectForKey:@"longtitude"]);

//        CLLocationCoordinate2D location=CLLocationCoordinate2DMake(latitude, longitude);
//        
//        MKCoordinateRegion region=MKCoordinateRegionMakeWithDistance(location,span ,span );
//        MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
//        [_mapView setRegion:adjustedRegion animated:YES];
        
        CLLocationCoordinate2D coordinate = {[[dic objectForKey:@"latitude"] doubleValue],[[dic objectForKey:@"longtitude"] doubleValue]};
        float zoomLevel =0.15; //设置显示精度
        //确定显示初始位置
        MKCoordinateRegion region =MKCoordinateRegionMakeWithDistance(coordinate,zoomLevel,zoomLevel);
           
            MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];

            [self.mapView setRegion:adjustedRegion animated:YES];
            [_mapView setCenterCoordinate:coordinate zoomLevel:11 animated:NO];
            self.mapView.centerCoordinate = coordinate;

        BasicMapAnnotation *  annotation=[[BasicMapAnnotation alloc] initWithLatitude:latitude andLongitude:longitude];
            annotation.name = [dic objectForKey:@"name"];
            annotation.merchantId = [[dic objectForKey:@"ID"] intValue];
            if([dic valueForKey:@"cuisine"] != [NSNull null])
                annotation.cuisine = [dic objectForKey:@"cuisine"];
            else
                annotation.cuisine = @"未知";
            annotation.address = [dic objectForKey:@"address"];
            if([dic valueForKey:@"score"] != [NSNull null])
                annotation.score = [[dic objectForKey:@"score"] floatValue];
            else
                annotation.score = 0;
        [_mapView   addAnnotation:annotation];
        }
    }
}


- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
	if ([view.annotation isKindOfClass:[BasicMapAnnotation class]]) {
        if (_calloutAnnotation.coordinate.latitude == view.annotation.coordinate.latitude&&
            _calloutAnnotation.coordinate.longitude == view.annotation.coordinate.longitude) {
            return;
        }
        if (_calloutAnnotation) {
            [mapView removeAnnotation:_calloutAnnotation];
            _calloutAnnotation = nil;
        }
        _calloutAnnotation = [[CalloutMapAnnotation alloc]
                               initWithLatitude:view.annotation.coordinate.latitude
                               andLongitude:view.annotation.coordinate.longitude];
//        _calloutAnnotation.name = ((BasicMapAnnotation *)view.annotation).name;
        name = ((BasicMapAnnotation *)view.annotation).name;
        address = ((BasicMapAnnotation *)view.annotation).address;
        cuisine = ((BasicMapAnnotation *)view.annotation).cuisine;
        score = ((BasicMapAnnotation *)view.annotation).score;
        merchantId = ((BasicMapAnnotation *)view.annotation).merchantId;
        [mapView addAnnotation:_calloutAnnotation];
        
        [mapView setCenterCoordinate:_calloutAnnotation.coordinate animated:YES];
	}
    else{
//        NSLog(@"%@",@"点击至之后你要在这干点啥");
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数        
        view.merchantId =merchantId;
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        //        [view release];

//        if([delegate respondsToSelector:@selector(customMKMapViewDidSelectedWithInfo:)]){
//            [delegate customMKMapViewDidSelectedWithInfo:@"点击至之后你要在这干点啥"];
//        }
    }
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    if (_calloutAnnotation&& ![view isKindOfClass:[CallOutAnnotationVifew class]]) {
        if (_calloutAnnotation.coordinate.latitude == view.annotation.coordinate.latitude&&
            _calloutAnnotation.coordinate.longitude == view.annotation.coordinate.longitude) {
            [mapView removeAnnotation:_calloutAnnotation];
            _calloutAnnotation = nil;
        }
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	if ([annotation isKindOfClass:[CalloutMapAnnotation class]]) {
        
        CallOutAnnotationVifew *annotationView = (CallOutAnnotationVifew *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CalloutView"];
        if (!annotationView) {
            annotationView = [[CallOutAnnotationVifew alloc] initWithAnnotation:annotation reuseIdentifier:@"CalloutView"];
           
        }
//        JingDianMapCell  *cell = (JingDianMapCell *) [annotationView.contentView dequeueReusableAnnotationViewWithIdentifier:@"JingDianMapCell"];
//        if(!cell)
        for (UIView *subView in [annotationView.contentView subviews]){
            if ([subView isKindOfClass:[JingDianMapCell class]])
                [subView removeFromSuperview];
        }
        JingDianMapCell  *cell = [[[NSBundle mainBundle] loadNibNamed:@"JingDianMapCell" owner:self options:nil] objectAtIndex:0];
        cell.score = [NSNumber numberWithFloat:score];
        cell.lbName.text =name;// ((CalloutMapAnnotation*)annotation).name;
        cell.lbAddress.text = address;
        cell.lbCuisine.text = cuisine;
        
        [annotationView.contentView addSubview:cell];
        return annotationView;

	} else if ([annotation isKindOfClass:[BasicMapAnnotation class]]) {
        MKAnnotationView *annotationView =[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotation"];
        if (!annotationView) {
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                           reuseIdentifier:@"CustomAnnotation"];
            annotationView.canShowCallout = NO;
//            annotationView.image = [UIImage imageNamed:@"pin.png"];
            ((MKPinAnnotationView *)annotationView).pinColor = MKPinAnnotationColorRed;
        }
		
		return annotationView;
    }
	return nil;
}
- (void)resetAnnitations:(NSArray *)data
{
    [_annotationList removeAllObjects];
    [_annotationList addObjectsFromArray:data];
    [self setAnnotionsWithList:_annotationList];
}
- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
//- (void)customMKMapViewDidSelectedWithInfo:(id)info
//{
//    NSLog(@"%@",info);
//}
@end

/*
#import "MapResultViewController.h"
#import "Config.h"
#import "RestaurantDetailViewController.h"
@interface MapResultViewController ()

@end

@implementation MapResultViewController
@synthesize map;
@synthesize results;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initMap];
}

- (void)viewDidUnload
{
    [self setMap:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void) initMap
{
    CLLocationCoordinate2D coordinate = {[[Config Instance]getLatitude],[[Config Instance]getLongitude]};
    float zoomLevel =0.2; //设置显示精度
    //确定显示初始位置
    MKCoordinateRegion region =MKCoordinateRegionMake(coordinate,MKCoordinateSpanMake(zoomLevel, zoomLevel));
    [self.map setRegion:region animated:YES];
    self.map.centerCoordinate = coordinate;
    map.delegate = self;
    
    for(int i=0;i<results.count;i++){
        NSDictionary * dic = [results objectAtIndex:i];
        if([dic valueForKey:@"latitude"] != [NSNull null]){
          
            //为地图添加注解
            CLLocationCoordinate2D coordinate = {[[dic valueForKey:@"latitude"] floatValue], [[dic valueForKey:@"longtitude"] floatValue]};
//            float zoomLevel =0.2; //设置显示精度
//            //确定显示初始位置
//            MKCoordinateRegion region =MKCoordinateRegionMake(coordinate,MKCoordinateSpanMake(zoomLevel, zoomLevel));
//            [self.map setRegion:region animated:YES];
//            
//            self.map.centerCoordinate = coordinate;
            ASPin *pin =[[ASPin alloc]initWithCoordinate:coordinate];
            pin.tips = [dic valueForKey:@"name"];
            pin.address =  [dic valueForKey:@"address"];
            pin.cuisine = [dic valueForKey:@"cuisine"];
            pin.merchantId = [[dic valueForKey:@"ID"] intValue];
            [self.map addAnnotation: pin];
            [pin release];
            
        }
    }
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
    [map release];
    [super dealloc];
}
#pragma mark - MKMapViewDelegate

//添加注解
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    MKPinAnnotationView *pinView =nil;
    static NSString *defaultPinID =@"AS.PIN";
    
    pinView = (MKPinAnnotationView *)[self.map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
    if(pinView==nil)
    {
        pinView = [[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:defaultPinID]autorelease];
//        pinView.pinColor = MKPinAnnotationColorGreen;
        pinView.canShowCallout =YES; //是否点击显示注释文字
        pinView.animatesDrop =NO;
    }
    return pinView;
    
}


//当用户点击小人图标的时候，就进入这里，即将显示 AnnotationView
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
	
	if ([view.annotation isKindOfClass:[ASPin class]]==NO)
	{
		return  ;
	}
	
    //设置显示的视图的内容
    ASPin *  annotation=(ASPin *) view.annotation;
    //通过MapAnnotation就可以获得自己设置的一些个性化信息。
    //然后，根据这些信息来设置，这里是获得头像的文件路径，然后
    //设置到 VIEW
    UIImageView   *  headImageView=[[UIImageView  alloc] initWithImage:[UIImage   imageNamed:@"ic_star.png"] ];
    [headImageView  setFrame:CGRectMake(100, 80, 16, 16)];
    [headImageView  autorelease];
    [view addSubview:headImageView];
//    [headImageView    setImage:[UIImage  imageWithContentsOfFile: nsFilePath] ];
}
- (void) mapView:(MKMapView *)mapView   didAddAnnotationViews:(NSArray*) views
{
	int   i=0;
	for (MKPinAnnotationView     *mkview   in   views     )
	{
		//判断是否是自己
		if ([mkview.annotation isKindOfClass:[ASPin class]]==NO)
		{
			continue;
		}
		else
		{
            UIImageView   *  headImageView=[[UIImageView  alloc] initWithImage:[UIImage   imageNamed:@"ic_star.png"] ];
            [headImageView  setFrame:CGRectMake(100, 80, 16, 16)];
            [headImageView  autorelease];
            mkview.leftCalloutAccessoryView=headImageView;
//            [mkview setFrame:CGRectMake(mkview.frame.origin.x , mkview.frame.origin.y, mkview.frame.size.width, mkview.frame.size.height+30)];
            
            UIButton  *  rightbutton=[UIButton  buttonWithType:UIButtonTypeDetailDisclosure];
            mkview.rightCalloutAccessoryView=rightbutton;
		}
		i++;
	}
	
}

-(void) mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view  calloutAccessoryControlTapped:(UIControl *) control
{
	ASPin  *   annotation= view.annotation;
    RestaurantDetailViewController  *view1 = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
    //传递商户id参数    
    view1.merchantId = annotation.merchantId;
    view1.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view1 animated:YES];
    [view1 release];
    // 根据 MapAnnotation,取出个性化的个人信息，然后创建自己
    // 的新的VIEW,并且显示。
    
}
@end
*/